package com.radon.config;

import com.radon.util.Constant;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置信息(此文件可省略)
 * @ConfigurationProperties(prefix = "spring.rabbitmq")
 */
@Configuration
@EnableRabbit
public class RabbitMQConfig {

    //基础信息
    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHosthost;

    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms;
    
    @Value("${spring.rabbitmq.publisher-returns}")
    private boolean publisherReturns;
    /**
     * 注册连接类
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host,port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHosthost);
        connectionFactory.setPublisherConfirms(publisherConfirms);//是否开启发布确认
        connectionFactory.setPublisherReturns(publisherReturns); //失败返回
        return connectionFactory;
    }

    /**
     *  跟spring整合注入改模板，跟springboot整合的话只需要在配置文件中配置即可
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    /**
     * 默认模板
     * @return
     */
    @Bean(name="defauilTemplate")
    public RabbitTemplate rabbitTemplateDefault() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setDefaultReceiveQueue(Constant.QueueEnum.DIRECT_QUEUE.getName());//设置默认接收队列
        return template;
    }
}
